import { login, logout, getInfo } from '@/api/login'


const user = {
  state: {
    name: '',
    number: '',
    avatar: '',
    roles: [],
    id: ''
  },

  mutations: {
    SET_ID: (state, id) => {
      state.id = id;
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_NUMBER: (state, number) => {
      state.number= number
    }
  },

  actions: {
    // 登录
    Login({ commit, state }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise(async (resolve, reject) => {
        try {
          const data = await login(username, userInfo.password)
          console.log(data)
          commit('SET_ID', data.id)
          commit('SET_ROLES', data.role)
          commit('SET_NUMBER', data.number)
          resolve(data);
        } catch (e) {
          reject(e);
        }
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_ID', '')
          commit('SET_ROLES', [])
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
